public class Test {

    public static int searchInsert(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while(left < right) {
            int mid = (left + right) / 2;
            if(nums[mid] == target) {
                return mid;
            } else if(nums[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        if(nums[left] == target) {
            return left;
        } else if(nums[left] < target) {
            return left + 1;
        }

        if(left - 1 == -1) {
            return 0;
        }
        return left;
    }

    public int mySqrt(int x) {
        long left = 0;
        long right = x;
        while(left < right) {
            long mid = left + (right - left) / 2;
            if(mid * mid < x) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        if(right * right == x) {
            return (int)right;
        }

        return (int)right - 1;
    }

    public int peakIndexInMountainArray(int[] arr) {
        int left = 0;
        int right = arr.length - 1;
        while(left < right) {
            int mid = left + (right - left + 1) / 2;
            if(arr[mid - 1] < arr[mid]) {
                left = mid;
            } else {
                right = mid - 1;
            }
        }

        return left;
    }

    public int findMin(int[] nums) {
        int left = 0;
        int right = nums.length - 1;
        int last = nums[right];
        while(left < right) {
            int mid = left + (right - left) / 2;
            if(nums[mid] > last) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        return nums[left];
    }

    public int takeAttendance(int[] records) {
        int left = 0;
        int right = records.length - 1;
        while(left < right) {
            int mid = left + (right - left) / 2;
            if(records[mid] == mid) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        return left == records[left] ? left + 1 : left;
    }

    public static void main(String[] args) {
        int[] nums = {1,3};
        int target = 2;
        System.out.println(searchInsert(nums, target));
    }
}
